Step 4: Hello Node

The most common example Hello World of Node.js is a web server! Update the server.js as follows:

import http from "http";

const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello Node\n");
});

server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

The createServer() method of http creates a new HTTP server and returns it.

The server is set to listen on the specified port. When the server is ready, the callback function is called, in this case informing us that the server is running.

Whenever a new request is received, the [request event](https://nodejs.org/api/http.html#http_event_request) is called, providing two objects:

  • a request (an [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object) and,
  • a response (an [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) object)

Those 2 objects are essential to handle the HTTP call. The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data. The second is used to return data to the caller.

Run the server with yarn start and then visit http://localhost:3000/. You must see the “Hello Node” message in the browser!

The call to server.listen causes the "server" (your computer in this case) to start waiting for requests on port 3000. This is why you have to connect to localhost:3000 to "speak" to this server, rather than just localhost, which would use the default port 8080.

When you run this script, the process sits there and waits. When a process is listening for events (in this case, network connections) node will not automatically exit when it reaches the end of the script. To close it, press Ctrl + C.